<!--编辑生产数据-->
<template>
  <div class="edit-produce-data-wrap">
    <addDetail :title="title" :disabled="disabled" :type="type" :produceDataDetail="produceDataDetail" @update="getData" @autofill="getFillData" />
    <toast v-model="show2" width="14em">
      <div>
        <p>{{ text1 }}</p>
        <p>{{ text2 }}</p>
      </div>
    </toast>
  </div>
</template>

<script>
import addDetail from './addDetail.vue';
import ProduceDataDao from '@/daos/produce_data_dao';
import { Toast } from 'vux';
import dayjs from 'dayjs';
export default {
  name: 'editProduceData',
  data() {
    return {
      produceDataDetail: {
        departmentId: '',
        fillTime: '',
        departmentName: '',
        orgId: '',
        orgJobShiftId: '',
        orgJobShiftName: '',
        members: '',
        userName: '',
        userId: '',
        status: '',
        output: '',
        sectionList: [],
      },
      id: '',
      type: 'edit',
      message: '',
      disabled: false,
      title: '编辑生产数据',
      show1: false,
      show2: false,
      text1: '',
      text2: '',
      timer: null,
      auto: 0,
      percentage: 0,
      hasFillData: 0,
      store: {},
    };
  },

  components: {
    addDetail,
    Toast,
  },

  computed: {},
  activated() {
    this.id = this.$route.query.id;
    this.message = this.$route.query.message || '';
    if (this.$route.query.see) {
      this.type = 'see';
      this.disabled = true;
      this.title = '查看生产数据';
    }
    this.getData();
  },

  methods: {
    initWx() {
      if (typeof wx !== 'undefined') {
        let localUrl = location.href.split('#')[0];
        this.$http(this.$API.getWxSign, { url: encodeURIComponent(localUrl) }, true).then((res) => {
          if (res) {
            wx.config({
              debug: false,
              appId: res.appId, // 必填,公众号的唯一标识
              timestamp: res.timestamp, // 必填,生成签名的时间戳
              nonceStr: res.nonceStr, // 必填,生成签名的随机串
              signature: res.signature, // 必填,签名
              jsApiList: [
                'updateAppMessageShareData',
                'updateTimelineShareData',
                'onMenuShareAppMessage', //旧的接口，即将废弃
                'onMenuShareTimeline', //旧的接口，即将废弃
              ], // 必填,需要使用的JS接口列表
            });
            /* 处理失败验证 */
            wx.error(function(res) {
              console.log('res:====>', res);
              // config 信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名
            });
            wx.ready(() => {
              let shareData = {
                title: `${this.produceDataDetail.departmentName}${dayjs(this.produceDataDetail.fillTime).format('YYYY年MM月DD日')}【${this.produceDataDetail.orgJobShiftName}】生产数据`, // 分享标题
                desc: `填报人：${this.produceDataDetail.userName}\r\n本班人员：${this.produceDataDetail.members}`, // 分享描述
                link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: 'https://static-a1b2.iuyun.com/0e7c863e-e8e1-4dce-8052-d2513c9ebc6b.png', // 分享图标
                success: function() {
                  // 用户点击了分享后执行的回调函数
                  console.log('success');
                },
              };
              wx.updateAppMessageShareData(shareData);
              wx.updateTimelineShareData(shareData);
              try {
                wx.onMenuShareAppMessage(shareData);
                wx.onMenuShareTimeline(shareData);
              } catch (e) {}
            });
          }
        });
      }
    },
    getData() {
      ProduceDataDao.getProduceDetail(
        { id: this.id, isAuth: this.message ? 0 : 1 },
        (res) => {
          if (res) {
            let store = JSON.parse(localStorage.getItem('ProduceData' + res.id));
            if (store && store.id === res.id) {
              this.produceDataDetail = store;
              this.initWx();
            } else {
              res.sectionList.forEach((item) => {
                item.detailList.forEach((sItem) => {
                  sItem.parkingList = sItem.parkingList || [];
                  sItem.seriesParamsArray = JSON.parse(sItem.data);
                });
              });
              this.produceDataDetail = res;
              this.initWx();
            }
          }
        },
        (desc) => {
          this.$vux.toast.show({ text: desc, type: 'warn' });
          setTimeout(() => {
            this.$router.push('/produceData');
          }, 500);
        }
      );
    },
    getFillData(tag = 0) {
      // 显示
      ProduceDataDao.getFillData(
        {
          dataTime: this.produceDataDetail.fillTime,
          departmentId: this.produceDataDetail.departmentId,
          orgJobShiftId: this.produceDataDetail.orgJobShiftId,
        },
        (res) => {
          if (!tag) {
            this.produceDataDetail = JSON.parse(JSON.stringify(this.store.produceDataDetail));
          }
          this.fillData(res);
          if (!tag) {
            this.text1 = this.hasFillData ? '获取成功' : '未获取到上报数据';
            this.text2 = this.hasFillData ? '5s内跳转到添加数据页' : '请手动添加数据';
          } else {
            this.text1 = this.hasFillData ? '获取成功' : '未获取到上报数据';
          }
          this.show2 = true;
          this.show1 = false;
          clearInterval(this.timer);
          setTimeout(() => {
            this.auto = 2;
            this.show2 = false;
          }, 1000);
        }
      );
    },
    fillData(res) {
      this.hasFillData = 0;
      if (res) {
        let autocomplete = {};
        res.sectionList.forEach((item, index) => {
          item.sectionSeriesList.forEach((sItem, sIndex) => {
            if (sItem.sectionFieldList) {
              sItem.sectionFieldList.forEach((ssItem, ssIndex) => {
                if (ssItem.fillData && !this.hasFillData) {
                  this.hasFillData++;
                }
                if (ssItem.fillData) {
                  this.produceDataDetail.sectionList[index].detailList[sIndex].seriesParamsArray[ssIndex].value = ssItem.fillData;
                }

                // 需增加自动计算:原矿处理量=精料班产量+甩废班产量
                if (ssItem.fillData && (ssItem.fieldCode === 'jingliao_quantity' || ssItem.fieldCode === 'shaifei_quantity')) {
                  autocomplete[ssItem.fieldCode] = ssItem.fillData;
                }

                if (ssItem.fieldCode === 'yuankuang_rhandle_quantity') {
                  autocomplete[ssItem.fieldCode] = [index, sIndex, ssIndex];
                }
              });
            }
          });
        });

        if (autocomplete['jingliao_quantity'] && autocomplete['shaifei_quantity']) {
          let index = autocomplete['yuankuang_rhandle_quantity'];
          let sum = (+autocomplete['jingliao_quantity'] || 0) + (+autocomplete['shaifei_quantity'] || 0);
          if (index.length) {
            this.produceDataDetail.sectionList[index[0]].detailList[index[1]].seriesParamsArray[index[2]].value = sum;
          }
        }
        // this.produceDataDetail.sectionList = res.sectionList;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.edit-produce-data-wrap {
  background: #1c1f37;
  min-height: 100%;
}
</style>
